//loading
//var alltxt = "";
var searchtxt = []; //搜索结果
var arr1 = [];
var arr = ["list_1.jpg", "list_2.jpg", "list_3.jpg", "list_4.jpg", "list_5.jpg", "list_6.jpg", "list_7.jpg", "list_8.jpg", "list_9.jpg", "list_10.jpg", "query_bg1.jpg"];
function fnLoad() {
    for (var i = 0; i < arr.length; i++) {
        var oImg = new Image();
        /*创建图片实例*/
        oImg.src = "images/buy/" + arr[i];
    }
    oImg.onload = function () {
        for (var i = 0; i < arr.length; i++) {
            arr1.push(arr[i]);
        }
        if (arr1.length == arr.length) {
            $(".progress").fadeOut();
        }
    };
}
fnLoad();
//添加城市
var province = "";
var province1 = "";
var city = "";
var len = Math.ceil(provinces.length / 2);
for (var i = 0; i < len; i++) {
    province += "<tr>";
    province += "<td>";
    province += provinces[i][2];
    province += "</td>";
    province += "<td class='two'>";
    for (var q = 0; q < citys.length; q++) {
        if (provinces[i][1] == citys[q][0]) {
            province += "<span>" + citys[q][2] + "</span>";
        }
    }
    province += "</td>";
    province += "</tr>";
}
for (var j = len; j < provinces.length; j++) {
    province1 += "<tr>";
    province1 += "<td>";
    province1 += provinces[j][2];
    province1 += "</td>";
    province1 += "<td class='two'>";
    for (var w = 0; w < citys.length; w++) {
        if (provinces[j][1] == citys[w][0]) {
            province1 += "<span>" + citys[w][2] + "</span>";
        }
    }
    province1 += "</td>";
    province1 += "</tr>";
}
$(".table_one").append(province);
$(".table_two").append(province1);
//地图
var map = new AMap.Map('container', {
    resizeEnable: true,
    zoom: 13,
    center: [116.397428, 39.90923],//地图中心点
});

//定位
var city_code = '010';
map.plugin('AMap.Geolocation', function () {
    geolocation = new AMap.Geolocation({
        enableHighAccuracy: true,//是否使用高精度定位，默认:true
        timeout: 10000,          //超过10秒后停止定位，默认：无穷大
        buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
        zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
        buttonPosition: 'RB'
    });
    map.addControl(geolocation);
    geolocation.getCurrentPosition();
    AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
    AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
});



//自动完成服务
AMap.service(["AMap.Autocomplete"], function () {
    var input = document.getElementById('stxt');
    var placeAuto = new AMap.Autocomplete({ //构造地点查询类
        input: "stxt"
    });
    AMap.event.addListener(placeAuto, 'complete', onAutoComplete);//返回定位信息
    AMap.event.addListener(placeAuto, 'select', onAutoSelect);
    AMap.event.addListener(placeAuto, 'error', onAutoError);      //返回定位出错信息
    AMap.event.addListener(placeAuto, 'listElementClick', onAutoChoose);      //返回定位出错信息
    placeAuto.search(input.value)
});

function onAutoComplete(data) {
    console.log(data);

}

function onAutoError(data) {
    console.log(data);
}

function onAutoSelect(data) {
    data.position = data.poi.location;
    getStore(data);
    console.log(data);
}

function onAutoChoose(data) {
    console.log(data);
}

//解析定位结果
function onComplete(data) {
    console.log(eval(data));
    //map.setCenter(data.position.getLng(), data.position.getLat());
    var str = ['定位成功'];
    str.push('经度：' + data.position.getLng());
    str.push('纬度：' + data.position.getLat());
    str.push('精度：' + data.accuracy + ' 米');
    str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
    console.log('定位信息:' + str);
    getStore(data);


    //document.getElementById('tip').innerHTML = str.join('&lt;br&gt;');
}
//解析定位错误信息
function onError(data) {
    console.log(data);
    //document.getElementById('tip').innerHTML = '定位失败';
}
function getStore(data) {
    map.clearMap();
    map.setZoomAndCenter(13, data.position);
    var lnglat = new AMap.LngLat(data.position.getLng(), data.position.getLat());
    var fresh = Math.random();
    var city = '';
    if (data.addressComponent != null) {
        city_code = data.addressComponent.citycode;
        city = data.addressComponent.province + ',' + data.addressComponent.city;
    }
    invokeApi("website/getStore", {
        "lng": data.position.getLng(),
        "city": city,
        "lat": data.position.getLat(),
        "fresh": fresh
    },"", function (ret) {
        var this_DATA_RETURN = eval(ret);
        var this_DATA = eval(this_DATA_RETURN.DATAS);
        var markers = [];
        var store_list = [];
        console.log(this_DATA);
        searchtxt = []; //搜索结果
        for (var i = 0; i < this_DATA.length; i++) {
            var this_DATA_s = eval(this_DATA[i]);
            var km = (Math.round(lnglat.distance([this_DATA_s.longitude, this_DATA_s.latitude]) / 100) / 10).toFixed(1);
            if (lnglat.distance([this_DATA_s.longitude, this_DATA_s.latitude]) < 3001) {
                //alltxt += '<h3>' + this_DATA_s.store + ' ' + this_DATA_s.store_name + '</h3><p>' + this_DATA_s.address + '<em>< ' + this_DATA_s.distance + 'km</em></p>,';
                try {
                    var marker;
                    var icon = new AMap.Icon({
                        image: 'http://tva2.sinaimg.cn/crop.0.7.750.750.50/6cb58a66jw8f7d3kvhw0kj20ku0l8q3w.jpg',
                        size: new AMap.Size(24, 24)
                    });
                    marker = new AMap.Marker({
                        position: [this_DATA_s.longitude, this_DATA_s.latitude],
                        offset: new AMap.Pixel(-12, -12),
                        zIndex: 101,
                        title: this_DATA_s.store + this_DATA_s.store_name,
                        extData: this_DATA_s.address,
                        map: map
                    });

                    var item = {
                        store: this_DATA_s.store,
                        store_name: this_DATA_s.store_name,
                        address: this_DATA_s.address,
                        distance: km
                    };

                    store_list.push(item);
                    markers.push(marker);
                }
                catch (e) {
                    console.log('标记出错:' + e);
                }
            }

        }

        if (markers.length) {
            markers.forEach(function (value, index, array) {
                AMap.event.addListener(value, 'click', function () {
                    var info = [];
                    info.push("<div><div>乐纯购买门店</div> ");
                    info.push("<div style=\"padding:0px 0px 0px 4px;\">店名 :<b>" + value.getTitle() + "</b>");
                    info.push("距离 : " + (lnglat.distance(value.getPosition()) / 1000).toFixed(1) + "公里");
                    info.push("地址 :" + value.getExtData() + "</div></div>");
                    infoWindow = new AMap.InfoWindow({
                        content: info.join("<br/>")  //使用默认信息窗体框样式，显示信息内容
                    });
                    infoWindow.open(map, map.getCenter());
                });
            });
        }

        store_list.sort(function (a, b) {
            return a.distance - b.distance;
        });
        for (var j = 0; j < store_list.length; j++) {
            searchtxt.push('<h3>' + store_list[j].store + ' ' + store_list[j].store_name + '<em>< ' + store_list[j].distance + 'km</em></h3><p><span>' + store_list[j].address + '</span></p>');
        }
        //for (var j = 0; j <3; j++) {
        //    //alltxt += '<h3>11111<em>33333</em></h3><p><span>22222</span></p>,';
        //    searchtxt.push('<h3>11111<em>33333</em></h3><p><span>22222</span></p>');
        //}
        searchs();
    });
    map.setFitView();

}
//        关注
$(".alert_bg").height($(document).height());
$(".weixin,.mo_weixin").click(function () {
    $(".alert_box,.alert_bg").fadeIn(300);
    $("body").css("overflow", "hidden");
});
$(".x").click(function () {
    $(".alert_box,.alert_bg").fadeOut(300);
    $("body").css("overflow", "auto");
});
var swiper = new Swiper('.swiper-container', {
    pagination: '.swiper-pagination',
    slidesPerView: 'auto',
    loop: true,
    centeredSlides: true,
    paginationClickable: true,
    spaceBetween: 30
});
!(function () {
    $(window).scroll(function () {
        if ($(window).scrollTop() > 1000) {
            $("#go").css("display", "block");
        } else {
            $("#go").css("display", "none");
        }
        $("#go").click(function () {
            $("body").stop().animate({scrollTop: 0});
        })
    })
}());
var pcount = 3;//每页数量

function searchs() //搜索内容
{
    allpage = getpage();
    if (allpage > 5) {
        gopage(1, 5, 1);
    } else {
        gopage(1, allpage, 1);
    }
}
function getpage() { //获取总页数
    var len = searchtxt.length;
    var allcount = Math.ceil(len / pcount); //一共有几页
    return allcount;
}


function getlcont() { //获取最后一个页面的记录数
    var len = searchtxt.length;
    var allcount = len % pcount;
    return allcount;
}
function gopage(page, count, p) //跳转到第几个页面
{
    var tcount = 0;
    //var sch_all = searchtxt.split(',');
    var sch_all = searchtxt;
    allpage = parseInt(getpage());
    var showcont = "";
    lcont = getlcont();
    if (allpage == p && lcont < pcount && lcont != 0) {
        tcount = pcount * (p - 1) + lcont;
    }
    else if (allpage == p && lcont == 0) {
        tcount = pcount * p;
    }
    else {
        tcount = pcount;
    }
    showcont += "<ul id=\"list\">";
    if (allpage == p) {
        for (var i = (p - 1) * pcount; i < tcount; i++) {
            showcont += "<li>" + sch_all[i] + "</li>";
        }
    }
    else {

        for (var i = (p - 1) * pcount; i < tcount * p; i++) {
            showcont += "<li>" + sch_all[i] + "</li>";
        }
    }
    showcont += "</ul>";
    var pagelist = "";
    for (var i = page; i <= count; i++) {
        if (i == p) {
            pagelist += "<a class='cur'>" + i + "</a>";
        } else if (i > 0) {
            pagelist += "<a>" + i + "</a>";
        }
    }
 console.log(sch_all[0]);
    if(sch_all[0]==undefined){
        $("#show").html("【抱歉！未找到定位附近合作门店】");
        $(".pag").html("");
        return
    }else{
        document.getElementById("page").innerHTML = pagelist;
        document.getElementById("show").innerHTML = showcont;

    }
}
function go(p) //跳转到第几个页面
{
    var tcount = 0;
    //var sch_all = searchtxt.split(',');
    var sch_all = searchtxt;
    allpage = parseInt(getpage());
    var showcont = "";
    lcont = getlcont();
    if (allpage == p && lcont < pcount && lcont != 0) {
        tcount = pcount * (p - 1) + lcont;
    }
    else if (allpage == p && lcont == 0) {
        tcount = pcount * p;
    }
    else {
        tcount = pcount;
    }
    showcont += "<ul id=\"list\">";
    if (allpage == p) {
        for (var i = (p - 1) * pcount; i < tcount; i++) {
            showcont += "<li>" + sch_all[i] + "</li>";
        }
    }
    else {

        for (var i = (p - 1) * pcount; i < tcount * p; i++) {
            showcont += "<li>" + sch_all[i] + "</li>";
        }
    }
    showcont += "</ul>";
    document.getElementById("show").innerHTML = showcont;
}
$(document).on("click", "#page a", function () {
    var $eq = $(this).html();
    $(this).addClass("cur").siblings().removeClass("cur");
    go($eq);
});
$(".next").click(function () {
    allpage = parseInt(getpage());
    var pageNum = parseInt($(".cur").html());//获取当前页
    var pageAdd = ++pageNum;
    if (pageAdd >= allpage) {
        pageAdd = allpage;
    }
    pageDown(pageAdd, allpage);
});
$(".prev").click(function () {
    allpage = parseInt(getpage());
    var pageNum = parseInt($(".cur").html());//获取当前页
    if (pageNum > 1) {
        var pageReduce = --pageNum;
        pageDown(pageReduce, allpage);
    }
});
function pageDown(pageNum, pageCount) {
    switch (pageNum) {
        case 1:
            if (pageCount >= 5) {
                gopage(1, 5, 1);
            } else {
                gopage(1, pageCount, 1);
            }
            break;
        case 2:
            if (pageCount >= 5) {
                gopage(1, 5, 2);
            } else {
                gopage(1, pageCount, 2);
            }
            break;
        case pageCount - 1:
            gopage(pageCount - 4, pageCount, pageCount - 1);
            break;
        case pageCount:
            gopage(pageCount - 4, pageCount, pageCount);
            break;
        default:
            gopage(pageNum - 2, pageNum + 2, pageNum);
            break;
    }
}

